/*!
 * @brief       	使能HART_CLK_OUT的定时器，用于输入捕获，上升沿捕获，4次有效
 *
 * @param 				None
 *
 * @return				freq: 浮点型频率变量，单位为Hz
 */
float Get_HART_CLK_Cycle(void)
{
	uint32_t Count=0;
	float freq=0;
	TIM15_CH2_Flag=0;
	TIM15_CH2_Overflow=0;
	TIM15_CH2_Count[0]=0;
	TIM15_CH2_Count[1]=0;
	__HAL_TIM_SET_CAPTUREPOLARITY(&htim15, TIM_CHANNEL_2, TIM_INPUTCHANNELPOLARITY_RISING);	
	HAL_TIM_Base_Start_IT(&htim15);
	HAL_TIM_IC_Start_IT(&htim15, TIM_CHANNEL_2);
	
	while(TIM15_CH2_Flag<2);
	TIM15_CH2_Flag=0;
	Count=TIM15_CH2_Overflow*(0xFFFF+1)+TIM15_CH2_Count[1]-TIM15_CH2_Count[0];	
	freq=50000000.0f/Count;	
	TIM15_CH2_Overflow=0;
	TIM15_CH2_Count[0]=0;
	TIM15_CH2_Count[1]=0;
	
	printf("[INFO] HART_CLK: %0.4f Hz\n",freq);
	return freq;
}

/*!
 * @brief       	操作AD5700的HART调制/解调
 *
 * @param 	[in]	dat_buf: 要写入的数据，可以填NULL
 *         	[in]	size: 要写入的数据个数，单位byte
 *        	[in]	WriteNotRead: true，写入（调制），发送UART数据然后通过HART发出来
 *  							false，读取（解调），接收HART数据，解调以后以中断的方式接收UART数据
 *
 * @return				None
 */
void Ctrl_AD5700_HART(uint8_t *dat_buf,uint8_t size,bool WriteNotRead)
{
	if(WriteNotRead)
	{
		Disable_AD5700_RTS;
		delay_ms(1);
		HAL_UART_Transmit(&huart4,dat_buf,size,0xFFFF);
	}
	else
	{
		Enable_AD5700_RTS;
		delay_ms(1);
		HAL_UART_Receive_IT(&huart3,&RxBuffer,1);  //开启中断 填入的buf最好是HART专用的数据buf 全局变量 然后在回调里面也改成HART的buf
	}
}

/*!
 * @brief       	初始化AD5700
 *
 * @param 				None
 *
 * @return				None
 */
void Init_AD5700(void)
{
	//ADC检测	
	
	Enable_HART_CLK_CFG;
	//时钟检测
	Get_HART_CLK_Cycle();
	
	Disable_HART_CLK_CFG;
	
	Ctrl_AD5700_HART(NULL,0,false);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if(huart==&huart2)
  {		
		HAL_UART_Transmit(&huart2,&RxBuffer,1,0xFFFF);
		HAL_UART_Receive_IT(&huart2,&RxBuffer,1);
  }
	else if(huart==&huart3)
  {		
		HAL_UART_Transmit(&huart3,&RxBuffer,1,0xFFFF);
		HAL_UART_Receive_IT(&huart3,&RxBuffer,1);
  }
	else if(huart==&huart4)
  {		
//		HAL_UART_Transmit(&huart4,&UART4_RxBuffer[UART4_RxFlag],1,0xFFFF);
		UART4_RxFlag++;
		HAL_UART_Receive_IT(&huart4,&UART4_RxBuffer[UART4_RxFlag],1);
  }
	else if(huart==&huart5)
  {		
		HAL_UART_Transmit(&huart5,&RxBuffer,1,0xFFFF);
		if((RxBuffer>>5)==6)
		{
			load_dac=(RxBuffer&0x1F);
		}
		HAL_UART_Receive_IT(&huart5,&RxBuffer,1);
  }
}

